package cn.anl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static cn.anl.constant.GlobalConstant.RELEASE_RESOURCES;

/**
 * @author zhoujunming
 * @Description TODO
 * @date 2022/6/6 14:38
 * @email zhoujunming@bluemoon.com.cn
 */
@Order(1)
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //放行资源集合
        List<String> permitAllResources= new ArrayList<>(RELEASE_RESOURCES);
        String[] resourceArray=permitAllResources.toArray(new String[]{});
        //拦截配置
        http.csrf().disable().formLogin()
                .permitAll()
                .and()
                .requestMatchers().antMatchers("/oauth/token","/login/**","/logout/**","/oauth/authorize")
                .and()
                .authorizeRequests()
                .mvcMatchers(resourceArray).permitAll();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //秘密增强
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }


    /**
    * @Author 安奈
    * @Desc 密码加密规则
    */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
    * @Author 安奈
    * @Desc 授权管理配置
    */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}